package com.et.launch

import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.os.SystemClock.sleep
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.MutableLiveData
import com.et.launch.databinding.ActivityFullscreenBinding
import com.et.logger.ELog
import com.et.logger.TAGS
import com.et.util.shell
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityFullscreenBinding
    private val mutableTipLiveData = MutableLiveData<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ELog.d(TAGS.launch, "launch onCreate")
        ActivityFullscreenBinding.inflate(layoutInflater).apply {
            setContentView(root)
            binding = this
        }
        initView()
    }

    private suspend fun openVending(delaySecond: Int) = withContext(Dispatchers.Default) {
        sleep(1000L * delaySecond)
        val string = StringBuilder(512)
        shell("pm list packages", string, false)
        var packageName: String? = null
        string.split('&').apply {
            if (isNotEmpty()) {
                forEach {
                    when {
                        it.contains("com.et.u0") -> {
                            packageName = "com.et.u0"
                            return@forEach
                        }
                        it.contains("com.et.u1") -> {
                            packageName = "com.et.u1"
                            return@forEach
                        }
                        it.contains("com.et.u2") -> {
                            packageName = "com.et.u2"
                            return@forEach
                        }
                        it.contains("com.et.u3") -> {
                            packageName = "com.et.u3"
                            return@forEach
                        }
                    }
                }
            } else {
                mutableTipLiveData.postValue("pm list packages empty")
            }
        }
        if (packageName == null) {
            mutableTipLiveData.postValue("vending not install")
        } else {
            packageName?.let { it ->
                Intent().apply {
                    ELog.d(TAGS.launch, string.toString())
                    component = ComponentName(it, "$it.MainActivity")
                    putExtra("launch", "launch")
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    startActivity(this)
                }
            }
        }

//        Intent().apply {
//            component = ComponentName(
//                "com.et.machine",
//                "com.et.machine.service.StableService"
//            )
//            Log.d(TAGS.launch, "start service")
//            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
//                startService(this)
//            }
//        }
    }

    private fun initView() {
        mutableTipLiveData.observe(this) {
            binding.label.text = it
        }
    }

    override fun onResume() {
        super.onResume()
        ELog.d(TAGS.launch, "launch onResume")
        full()
        CoroutineScope(Dispatchers.Main).apply {
            launch {
                openVending(5)
                Toast.makeText(
                    this@MainActivity,
                    Thread.currentThread().name,
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    /**
     * Option for {@link #setSystemBarsBehavior(int)}: Window would like to remain
     * interactive when hiding navigation bars by calling {@link #hide(int)} or
     * {@link WindowInsetsAnimationControllerCompat#setInsetsAndAlpha(Insets, float, float)}.
     * <p>
     * When system bars are hidden in this mode, they can be revealed temporarily with system
     * gestures, such as swiping from the edge of the screen where the bar is hidden from. These
     * transient system bars will overlay app’s content, may have some degree of
     * transparency, and will automatically hide after a short timeout.
     */
    private fun full() {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        WindowInsetsControllerCompat(window, binding.root).let { controller ->
            controller.hide(WindowInsetsCompat.Type.systemBars())
            controller.systemBarsBehavior =
                WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
    }

    override fun onPause() {
        super.onPause()
        ELog.d(TAGS.launch, "launch onPause")
    }

}